﻿namespace MyAppAPI.Models.Pagination
{
    public static class PaginationService
    {
        /// <summary>
        /// 分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys"></param>
        /// <param name="json"></param>
        /// <param name="pagination"></param>
        /// <returns></returns>
        public static IQueryable<T> BasePager<T>(this IQueryable<T> entitys, ref BasePaginationModel pagination)
        {
            if (pagination != null)
                entitys = entitys.GetBasePagination(pagination);
            return entitys;
        }

        /// <summary>
        /// 获取分页后的数据
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="source">数据源IQueryable</param>
        /// <param name="pagination">分页参数</param>
        /// <returns></returns>
        private static IQueryable<T> GetBasePagination<T>(this IQueryable<T> source,BasePaginationModel pagination)
        {
            pagination.Total = source.Count();
            return source.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize);
        }
    }
}
